<?php

namespace App\Repository;

use App\Entity\Log;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Security;

/**
 * @method Log|null find($id, $lockMode = null, $lockVersion = null)
 * @method Log|null findOneBy(array $criteria, array $orderBy = null)
 * @method Log[]    findAll()
 * @method Log[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class LogRepository extends ServiceEntityRepository {
    private $security;

    public function __construct (ManagerRegistry $registry, Security $security) {
        parent::__construct($registry, Log::class);
        $this->security = $security;
    }

    /**
     * User: Gao
     * Date: 2020/4/3
     * Description: 记录日志
     * @param $log_type_id
     * @param $description
     * @param null $parameter
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function buildLog ($log_type_id, $description, $parameter = null) {
        $log = new Log();
        $log->setLogTypeId($log_type_id);
        $log->setDescription($description);
        if (!is_null($parameter)) {
            $log->setParameter(serialize($parameter));
        }
        if (is_object($this->security->getUser())) {
            $log->setAdminUserId($this->security->getUser()->getId());
        }
        $log->setIp($this->getClientIp());
        $log->setCreatedAt(new \DateTime());
        $this->getEntityManager()->persist($log);
        $this->getEntityManager()->flush();
    }

    /**
     * User: Gao
     * Date: 2020/4/3
     * Description: 获取客户端IP
     * @return array|false|mixed|string
     */
    private function getClientIp () {
        $ip = '0.0.0.0';

        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        }
        if (getenv('HTTP_X_REAL_IP')) {
            $ip = getenv('HTTP_X_REAL_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
            $ips = explode(',', $ip);
            $ip = $ips[0];
        } elseif (getenv('REMOTE_ADDR')) {
            $ip = getenv('REMOTE_ADDR');
        }

        return $ip;
    }
}
